<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 会员管理》消费者
 * @author Administrator
 */
class Consumer extends MY_Controller {
    /**
     * @var ConsumerUserModel
     */
	public $mConsumer;
    /**
     * @var
     */
	public $mOrder;
    /**
     * 积分
     * @var ConsumerMallModel
     */
	public $mMall;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){

		$data = array(
		    'county' => (int)get('county'),
				'title'=>'消费者管理',
                'gender' => $this->mConsumer->getGender()
		);

		$this->view('member/consumer/home', $data, 'datatable,select2,datepicker');
	}

    /**
     * 获取列表
     */
    public function getList(){

        $data = $this->mConsumer->adminGetList();
        foreach ($data['data'] as $k=>$v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<img width="100%" src="'.$img.'" class="img-wh" />';
            
            $data['aaData'][$k][] = $v['nickname']?$v['nickname']:'暂无昵称';
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = isset($v['realname']) ? $v['realname'] : '暂无';
            $data['aaData'][$k][] = $v['balance'];
            $data['aaData'][$k][] = $v['gender'] ? $this->mConsumer->getGender($v['gender']) : '保密';
            $data['aaData'][$k][] = dateFormat($v['addtime'],false);
            $data['aaData'][$k][] = isset($v['last_login_time']) ? date('Y-m-d H:i:s',$v['last_login_time']):'尚未登录';
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = "<a href='".getUrl('member/consumer/changeStatus?id=').$v['id']."' class='ajax-request-btn deco' alert-message='是否确认".$this->adminStatus($status)."'>".$this->adminStatus($v['status'],true)."</a>";
            $name = isset($v['nickname']) ? $v['nickname'] : $v['mobile'];
            $btnConfig = adminCreateBtn(array(
                'label' => ' 详情',
//                'icon' => '<i class="fa fa-file-o"></i>',
                'attr' => array(
                    'href' => getUrl('member/consumer/details?id='.$v['id']),
                    'class' => 'btn btn-xs green-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'member',
                    'key' => 'consumer-details'
                )
            ));

            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 编辑',
//                    'icon' => '<i class="fa fa-edit"></i>',
                    'attr' => array(
                        'href' => getUrl('member/consumer/edit?id='.$v['id']),
                        'class' => 'btn btn-xs default blue-stripe',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'member',
                        'key' => 'consumer-edit'
                    )
                ));

            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 删除',
//                    'icon' => '<i class="fa fa-times"></i>',
                    'attr' => array(
                        'href' => getUrl('member/consumer/delete?id='.$v['id']),
                        'class' => 'ajax-request-btn btn btn-xs default red-stripe',
                        'alert-message' => "确认是否删除消费者：".$name."？"
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'member',
                        'key' => 'consumer-delete'
                    )
                ));

            $data['aaData'][$k][] = $btnConfig;
        }

        unset($data['data']);
        echo json_encode($data);
    }

	/**
	 * 详情
	 */
	public function details(){
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $this->loadModel('ConsumerMallModel', 'mMall', 'consumer');
        $this->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerExperienceValueModel', 'mExperience', 'consumer');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

		$tA = $this->mConsumer->getInfo(get('id'));
		if ( ! $tA){
			show_404();
		}
        //获取省份列表
        $province = $this->mAdm->getLocationByPid(1);
        //积分记录
        $integral_status = $this->mMall->config['status'];
        $integral_type = $this->mMall->config['type'];
        //账户资金记录
        $found_status = $this->mBuy->config['status'];
        $found_type = $this->mBuy->config['type'];

		$data = array(
            'title'=>'消费者详情',
            'add' => 1,
            'province' => $province,
            'integral_status' => $integral_status,
            'integral_type' => $integral_type,
            'found_status' => $found_status,
            'found_type' => $found_type,
            'info'=>$tA,
            'status' => $this->mOrder->status(),
            'bonusStatus' => $this->mPromotion->getBonusLogStatus(false),
            'expenseType' => $this->mOrder->expenseType(),
            'payType' => $this->mOrder->payType(),
            'serviceType' => $this->mOrder->serviceType(),
            'experienceType' => $this->mExperience->type
		);

		$this->view('member/consumer/details', $data, 'datatable,validation,select2,datepicker,region');
	}
	
	/**
	 * 增加
	 */
	public function add(){
		$data = array(
				'title'=>'消费者管理',
				'add'=>1,
		);
		
		$this->view('member/consumer/form', $data, 'validation,fileinput,select2,cropit_master');
	}
	
	/**
	 * 编辑
	 */
	public function edit(){

		$tA = $this->mConsumer->getInfo(get('id'));
		if ( ! $tA){
			show_404();
		}

		$data = array(
				'title'=>'消费者管理',
				'add'=>0,
				'info'=>$tA,
		);
		$this->view('member/consumer/form', $data, 'validation,fileinput,select2,cropit_master');
	}
	
	/**
	 * 保存数据
	 */
	public function save(){
		//表单验证
		$vConf = array(
				array('nickname', '昵称', 'required'),
				array('mobile', '手机号码', 'required|valid_mobile'),
				array('gender', '性别', 'required|in_list[1,2,3]'),
				array('status', '状态', 'required|in_list[1,2]'),
                array('password', '密码', 'min_length[6]|max_length[15]'),
		);
		$this->formDataValidation($vConf);

		$id = intval(post('id'));
		$mobile = trim(post('mobile'));
		$password = trim(post('password'));
		$repassword = trim(post('repassword'));
		$portrait = trim(post('portrait'));

		//验证手机号是否重复
        if($this->mConsumer->mobileIsExist($mobile, $id)){
            $this->ajaxReturn(0, '手机号码已经存在');
        }

        if($id){
            $info = $this->mConsumer->getInfo($id);
            if(!$info){
                $this->ajaxReturn(0, '消费者不存在');
            }
        }

        $aDate = array(
            'nickname' => trim(post('nickname')),
            'realname' => trim(post('realname')),
            'mobile' => trim(post('mobile')),
            'gender' => intval(post('gender')),
            'status' => intval(post('status'))
        );
        if(!$aDate['nickname']){
            $aDate['nickname'] = substr($aDate['mobile'],0,3).'****'.substr($aDate['mobile'], -4);
        }
        $this->db->trans_begin();
        $jpush_code = uniqid().rand(1000, 9999).rand(100, 9999);
        if(!$id){
            if(!$password) $this->ajaxReturn(0, '请设置登录密码');
            if($password != $repassword)$this->ajaxReturn(0, '密码不一致');

            $aDate['addtime'] = time();
            $aDate['jpush_code'] = $jpush_code;
            $aDate['balance'] = 0;
            $aDate['password'] = setPassword($password);
            $id = $this->mConsumer->save($aDate);
            if( ! $id){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }

            //注册环信账号
            $result = easemob($easemobName = $aDate['jpush_code'], $easemobword = $mobile.$id );

            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0,'注册失败:'.$result['error']);
            }
        }

        if($id && $password){
            if($password != $repassword)$this->ajaxReturn(0, '密码不一致');
            $aDate['password'] = setPassword($password);
        }

        //上传头像
        if($portrait){
            $path = 'uploads/member/consumer/'.$id.'/portrait';
            $tA = saveCSVimg(array($portrait), $path, 'portrait');

            if( ! $tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '头像上传失败');
            }
            $aDate['portrait'] = $tA[0];
        }

        if( ! ($query = $this->mConsumer->save($aDate, $id))) {
            $this->db->trans_rollback();
            $this->ajaxReturn(0,'保存失败');
        }
//        if (!$id) {
//            //注册环信账户
//            $res = easemob($jpush_code, $mobile . $id);
//            if (!$res['status']) {
//                $this->appReturn(0, '注册失败');
//            }
//        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', NULL, getUrl('member/consumer'));
	}
	
	/**
     * 删除消费者
     */
	public function delete(){
	    $id = intval(get('id'));
	    //获取消费者信息
        $info = $this->mConsumer->getInfo($id);
        if(!$info){
            $this->ajaxReturn(0, '消费者不存在');
        }
        if(!($this->mConsumer->save(array('status' => -1),$id))){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 删除消费者红包
     */
    public function deleteBonus(){
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');

        $id = intval(get('id'));
        //获取消费者信息
        $this->db->select('id,order_id,status')
                ->where('id', $id);
        $info = $this->mPromotion->getOne($this->mPromotion->tbBonusLog);
        if(!$info){
            $this->ajaxReturn(0, '红包不存在');
        }
        if($info['order_id'] > 0 || $info['status'] == 2){
            $this->ajaxReturn(0, '该红包已使用');
        }
        //删除
        $this->db->where('id', $id);
        if(!($this->mPromotion->delete($this->mPromotion->tbBonusLog))){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功', 'bonus');
    }
/*********************************************订单管理*****************************************************************/

    /**
     * 订单列表
     */
    public function orderList(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $id = (int)get('consumer_id');
        $data = $this->mOrder->adminPcGetOrderList(0, $id);
        if ($data['data']){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $v['code'];
                $data['aaData'][$k][] = $v['merchant'];
                $data['aaData'][$k][] = $this->mOrder->expenseType($v['expense_type']);
                $data['aaData'][$k][] = $v['total_amount'];
                $data['aaData'][$k][] = $v['reality_amount'];
                $data['aaData'][$k][] = $this->mOrder->payType($v['pay_type']);
                $data['aaData'][$k][] = dateFormat($v['addtime']);
                if ($v['expense_type'] == 2) {
                    $data['aaData'][$k][] = $this->mOrder->storeStatus($v['status'], true);
                } else {
                    $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
                }

                $btnConfig = adminCreateBtn(array(
                    'label' => '查看',
                    'attr' => array(
                        'href' => getUrl('member/consumer/orderDetails?id='.$v['id']),
                        'class' => 'btn green-stripe btn-xs default'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'classes',
                        'key' => 'edit'
                    )
                ));
                if ($v['status'] == 7){
                    $btnConfig .=' '.adminCreateBtn(array(
                            'label' => '删除',
                            'attr' => array(
                                'href' => getUrl('order/home/deleteOrder?id='.$v['id']),
                                'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                                'alert-message' => '是否确认删除订单？'
                            ),
                            'tag' => 'a',
                            'permissions' => array(
                                'module' => 'group',
                                'key' => 'status'
                            )
                        ));
                }
                $data['aaData'][$k][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 订单详情
     */
    public function orderDetails(){
        $id = get('id');
        if( ! is_numeric($id)){
            show_404();
        }
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $this->loadModel('AdmShippingModel', 'mShipping', 'admin');
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $info = $this->mOrder->getInfo($id);  // 订单信息
        if (empty($info)){
            show_404();
        }
        $oP = $this->mOrder->getOrderProductInfoByIds(array(), $id); // 订单商品信息
        if ($info['expense_type'] == 2){
            $buttons = $this->mOrder->storeStatus($info['status'], false, true); // 操作按钮
        }else{
            $buttons = $this->mOrder->status($info['status'], false, true); // 操作按钮
        }
        $province = $this->mAdm->getLocationByPid(1);  // 获取省份
        $ship = $this->mShipping->getList();    // 获取快递公司

        $reason = $this->mAdm->get('aftersale_reason');
        $data = array(
            'info' => $info,
            'oP' => empty($oP) ? array() : $oP[$id],
            'buttons' => $buttons,
            'province' => $province,
            'ship' => $ship,
            'reason' => json_decode($reason,true),
            'kd' => array(),
            'backUrl' => getUrl('member/consumer/details?id='.$info['consumer_id']),
            'title' => '订单详情'
        );
        $this->view('order/details', $data, 'datatable,validation,region,select2,webuploader');
    }

/*********************************************售后订单*****************************************************************/

    /**
     * 获取售后列表
     */
    public function serviceList(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $consumerId = (int)get('consumer_id');
        $data = $this->mOrder->adminPcGetOrderServiceList(0, $consumerId);
        if ($data['data']){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $v['code'];
                $data['aaData'][$k][] = $v['order_code'];
                $data['aaData'][$k][] = $v['name'];
                $data['aaData'][$k][] = $v['remark'];
                $data['aaData'][$k][] = $v['refund_amount'];
                $data['aaData'][$k][] = dateFormat($v['addtime']);
                $data['aaData'][$k][] = $this->mOrder->serviceType($v['status'], true);
                $btnConfig = adminCreateBtn(array(
                    'label' => '查看',
                    'attr' => array(
                        'href' => getUrl('member/consumer/serviceDetails?code='.$v['code']),
                        'class' => 'btn green-stripe btn-xs default'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'classes',
                        'key' => 'edit'
                    )
                ));
                $data['aaData'][$k][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 查看售后订单
     */
    public function serviceDetails(){
        $code = get('code');
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $serviceInfo = $this->mOrder->getServiceInfo($code);  // 售后信息
        if (empty($serviceInfo)){
            show_404();
        }
        $info = $this->mOrder->getInfo($serviceInfo['order_id']);  // 订单信息
        $oP = $this->mOrder->getOrderProductInfoByIds($serviceInfo['order_product_id'], $serviceInfo['order_id']); // 订单商品信息

        $data = array(
            'info' => $info,
            'serviceInfo' => $serviceInfo,
            'oP' => empty($oP) ? array() : $oP[$serviceInfo['order_product_id']],
            'backUrl' => getUrl('member/consumer/details?id='.$serviceInfo['consumer_id']),
            'title' => '售后详情'
        );
        $this->view('order/service/details', $data, 'datatable,validation,region,select2');
    }

/*********************************************收货地址*****************************************************************/

    /**
    * 收货地址
    * ————————————————————————————————————————————————————————
    */
    public function addressList(){
        $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');

        $data = $this->mAddress->adminGetList();

        $locationId = array();
        if($data){
            foreach ($data['data'] as $v){
                //省份
                if( ! in_array($v['province'], $locationId)){
                    $locationId[] = $v['province'];
                }
                //区
                if( ! in_array($v['city'], $locationId)){
                    $locationId[] = $v['city'];
                }
                //县
                if( ! in_array($v['county'], $locationId)){
                    $locationId[] = $v['county'];
                }
            }
            //获取区域名称
            $location = $this->mAdm->getLocationNameByIds($locationId);

            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $value['consignee'];
                $data['aaData'][$key][] = $value['mobile'];
                $data['aaData'][$key][] = $location[$value['province']]['name'].' - '.$location[$value['city']]['name'].' - '.$location[$value['county']]['name'];
                $data['aaData'][$key][] = $value['address'].$value['street'];
                $data['aaData'][$key][] = $value['latitude'].','.$value['longitude'];
                $btnConfig = adminCreateBtn(array(
                        'label' => ' 编辑',
//                        'icon' => '<i class="fa fa-edit"></i>',
                        'attr' => array(
                            'href' => getUrl('member/consumer/addressInfo?id='.$value['id'].'&consumer_id='.$value['consumer_id']),
                            'class' => 'btn btn-xs blue-stripe default edit-address-btn',
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'group',
                            'key' => 'edit'
                        )
                    ));

                $btnConfig .= ' '.adminCreateBtn(array(
                        'label' => ' 删除',
//                        'icon' => '<i class="fa fa-times"></i>',
                        'attr' => array(
                            'href' => getUrl('member/consumer/deleteAddress?id='.$value['id']).'&consumer_id='.$value['consumer_id'],
                            'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                            'alert-message' => "确认是否删除地址：".$v['address']."？"
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'group',
                            'key' => 'edit'
                        )
                    ));

                $data['aaData'][$key][] = $btnConfig;
            }
        }

        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 删除收货地址
     */
    public function deleteAddress(){
        $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        $id = intval(get('id'));
        $consumerId = intval(get('consumer_id'));
        //获取收货地址信息
        $info = $this->mAddress->getInfo($id, $consumerId);

        if(!$info){
            $this->ajaxReturn(0, '地址信息不存在');
        }
        //删除地址
        if(!($this->mAddress->deleteAddress($id, $consumerId))){
            $this->ajaxReturn(0, '删除失败');
        }

        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 保存收货地址
     */
    public function saveAddress(){
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        //表单验证
        $vConf = array(
            array('consumer_id', '消费者id', 'required|is_numeric'),
            array('province', '省份id', 'required|is_numeric'),
            array('city', '市id', 'required|is_numeric'),
            array('county', '区县id', 'required|is_numeric'),
            array('consignee', '收货人', 'required'),
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('gender', '性别', 'required|in_list[1,2]'),
            array('address', '详细地址', 'required'),
            array('street', '门牌号', 'required'),
        );
        $this->formDataValidation($vConf);

        $id = intval(post('id'));
        $consumer_id = intval(post('consumer_id'));
        //验证消费者
        $info = $this->mConsumer->getInfo($consumer_id);
        if(!$info){
            $this->ajaxReturn(0, '消费者不存在');
        }
        //验证收货地址
        if($id){
            $aInfo = $this->mAddress->getInfo($id, $consumer_id);
            if(!$aInfo){
                $this->ajaxReturn(0, '地址信息不存在');
            }
        }
        $data = array(
            'consumer_id' => $consumer_id,
            'consignee' => trim(post('consignee')),
            'mobile' => trim(post('mobile')),
            'gender' => intval(post('gender')),
            'address' => trim(post('address')),
            'street' => trim(post('street')),
            'province' => intval(post('province')),
            'city' => intval(post('city')),
            'county' => intval(post('county')),
        );

        //获取区域名称
        $locationId = array($data['province'],$data['city'],$data['county']);
        $aData = $this->mAdm->getLocationNameByIds($locationId);
        $address = $aData[$data['province']]['name'].$aData[$data['city']]['name'].$aData[$data['county']]['name'].$data['address'];

        //地址转换成坐标
        $localData = getLocation($address);
        if(!$localData){
            $this->ajaxReturn(0, '地址解析失败');
        }
        $data['latitude'] = $localData['lat'];
        $data['longitude'] = $localData['lng'];

        if(!$id){
            $data['addtime'] = time();
        }


        if(!($this->mAddress->save($data,$id))){
            $this->ajaxReturn(0, '保存失败');
        }

        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 获取地址信息
     */
    public function addressInfo(){
        $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');

        $id = intval(get('id'));
        $consumerId = intval(get('consumer_id'));

        //获取收货地址信息
        $info = $this->mAddress->getInfo($id, $consumerId);

        if(!$info){
            $this->ajaxReturn(0, '地址信息不存在');
        }

        echo json_encode($info);
    }

/*********************************************银行卡（支付宝）*********************************************************/

    /**
   * 银行卡（支付宝）
   * ————————————————————————————————————————————————————————
   */
    public function bankCardList(){

        $this->loadModel('ConsumerBankModel', 'mBank', 'consumer');

        $data = $this->mBank->adminGetList();

        if($data){

            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $this->mBank->getBankType($value['type']);
                $data['aaData'][$key][] = $value['account_name'];
                $data['aaData'][$key][] = $value['account_number'];
                $data['aaData'][$key][] = $value['open_bank'];
                $data['aaData'][$key][] = $value['mobile'];
                $data['aaData'][$key][] =  '';
            }
        }

        unset($data['data']);
        echo json_encode($data);
    }

/*********************************************积分明细*****************************************************************/

    /**
      * 积分明细
      * ————————————————————————————————————————————————————————
      */
    public function integralLogList(){
        $this->loadModel('ConsumerMallModel', 'mMall', 'consumer');

        $data = $this->mMall->adminGetListById();

        if($data){

            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $this->mMall->config['type'][$value['type']];
                $data['aaData'][$key][] = $value['code'];
                $data['aaData'][$key][] = $value['integral'];
                $data['aaData'][$key][] = $this->mMall->config['status'][$value['status']];
                $data['aaData'][$key][] =  '';
            }
        }

        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 保存积分记录
     */
    public function saveIntegral(){
        $this->loadModel('ConsumerMallModel', 'mMall', 'consumer');
        //表单验证
        $vConf = array(
            array('consumer_id', '消费者id', 'required|is_numeric'),
            array('amount', '金额', 'required|is_numeric'),
            array('type', '变动类型', 'required|in_list[1,2]')
        );
        $this->formDataValidation($vConf);

        $consumer_id = intval(post('consumer_id'));
        $type = intval(post('type'));//1 增加 2减少
        $amount = post('amount');
        if ($amount <= 0){
            $this->ajaxReturn(0, '调整金额必须大于零');
        }
        //验证消费者
        $info = $this->mConsumer->getInfo($consumer_id);
        if(!$info){
            $this->ajaxReturn(0, '消费者不存在');
        }
        if ($type == 2 && $info['integral'] < $amount){
            $this->ajaxReturn(0, '最大减少积分为'.$info['integral']);
        }

        $data = array(
            'consumer_id' => $consumer_id,
            'status' => 2,
            'type' => 7,
            'addtime' => time()
        );

        $consumer_balance = $info['integral'];
        if($type == 1){
            $data['integral'] = $amount;
            $consumer_balance += $amount;
        }else{
            $data['integral'] = '-'.$amount;
            $consumer_balance -= $amount;
        }

        //保存记录
        $this->db->trans_begin();
        if(!($this->mMall->saveLog($data))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        unset($data);

        //更新消费者账号余额
        if(!($this->mConsumer->save(array('integral' => $consumer_balance), $consumer_id))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功',array('integral' => $consumer_balance));
    }

/*********************************************资金明细*****************************************************************/

    /**
     * 资金明细
     * ————————————————————————————————————————————————————————
     */
    public function FoundLogList(){
        $this->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');

        $data = $this->mBuy->adminGetList();

        if($data){

            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $this->mBuy->config['type'][$value['type']];
                $data['aaData'][$key][] = $value['amount'];
                $data['aaData'][$key][] = $this->mBuy->config['status'][$value['status']];
                $data['aaData'][$key][] = dateFormat($value['addtime'],true);
                $btn = '';
                if($value['reason']){
                   $btn = '<a href="#" class="popovers" data-placement="left" data-trigger="hover" data-content="'
                    .$value['reason'].'" data-original-title="备注">[备注]</a>';
                }
                $data['aaData'][$key][] =  $btn;
            }
        }

        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 保存资金记录
     */
    public function saveFound(){
        $this->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
        //表单验证
        $vConf = array(
            array('consumer_id', '消费者id', 'required|is_numeric'),
            array('amount', '金额', 'required|is_numeric|less_than_equal_to[1000]'),
            array('reason', '备注', 'required'),
            array('type', '变动类型', 'required|in_list[1,2]')
        );
        $this->formDataValidation($vConf);

        $consumer_id = intval(post('consumer_id'));
        $type = intval(post('type'));//1 增加 2减少
        $amount = post('amount');
        if ($amount <= 0){
            $this->ajaxReturn(0, '调整金额必须大于零');
        }

//        if ($amount%100 != 0){
//            $this->ajaxReturn(0, '调整金额必须是100的倍数');
//        }
        //验证消费者
        $info = $this->mConsumer->getInfo($consumer_id);
        if(!$info){
            $this->ajaxReturn(0, '消费者不存在');
        }
        if ($type == 2 && $info['balance'] < $amount){
            $this->ajaxReturn(0, '最大减少金额为'.$info['balance']);
        }

        $data = array(
            'consumer_id' => $consumer_id,
            'status' => 2,
            'type' => 6,
            'pay_type' => 6,
            'reason' => trim(post('reason')),
            'addtime' => time(),
            'confirm_time' => time()
        );

        $consumer_balance = $info['balance'];
        if($type == 1){
            $data['amount'] = $amount;
            $consumer_balance += $amount;
        }else{
            $data['amount'] = '-'.$amount;
            $consumer_balance -= $amount;
        }

        if($consumer_balance > 5000){
            $this->ajaxReturn(0, '账户余额不能大于5000');
        }
        //保存记录
        $this->db->trans_begin();
        if(!($this->mBuy->save($data))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        //更新消费者账号余额
        if(!($this->mConsumer->save(array('balance' => $consumer_balance), $consumer_id))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        $title = '平台调整了您的资金：'.$data['amount'];
        $content = '平台调整了您的资金：'.$data['amount'];
        $msgData = array(
            'consumer_id' => $consumer_id,
            'type' => 2,
            'title' => $title,
            'content' => $content,
            'content_detail' => $data['reason'],
            'addtime' => time(),
        );
        $tA = $this->mMessage->save($msgData);
        if (!$tA){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '推送失败');
        }
        jpush($title, $content, 1, array($info['jpush_code']), $msgData['type'], $tA);
        unset($data);

        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功',array('balance' => $consumer_balance));
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mConsumer->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '消费者不存在');
        }
        $status = $info['status'] == 1 ? 2 : 1;
        $tA = $this->mConsumer->save(array('status' => $status), $id);
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

/*********************************************经验值明细***************************************************************/

    /**
     * 经验值明细
     */
    public function getExperienceValueList(){
        $this->loadModel('ConsumerExperienceValueModel', 'mExperience', 'consumer');

        $data = $this->mExperience->adminGetList();

        if($data){
            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $this->mExperience->type[$value['type']];
                $data['aaData'][$key][] = $value['experience_value'];
                $data['aaData'][$key][] = dateFormat($value['addtime']);
                $data['aaData'][$key][] =  '';
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 红包明细
     */
    public function getBonusValueList(){
        $id = get('consumer_id');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $data = $this->mPromotion->getUserBonusLogList($id);

        if($data){
            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $value['name'];
                $data['aaData'][$key][] = $value['money'];
                $data['aaData'][$key][] = $value['condition'];
                $data['aaData'][$key][] = dateFormat($value['addtime']);
                $data['aaData'][$key][] = dateFormat($value['use_end_time']);
               if ($value['status'] == 1 && $value['use_end_time'] <= time()){
                    $value['status'] = 3;
                }
                $data['aaData'][$key][] = $this->mPromotion->getBonusLogStatus($value['status'], true);
                $btnConfig = "";
                if(!($value['order_id'] > 0 || $value['status'] == 2)){
                    $btnConfig .= ' '.adminCreateBtn(array(
                            'label' => ' 删除',
                            'attr' => array(
                                'href' => getUrl('member/consumer/deleteBonus?id='.$value['id']),
                                'class' => 'ajax-request-btn btn btn-xs default red-stripe',
                                'alert-message' => "确认是否删除消费者红包：".$value['name']."？"
                            ),
                            'tag' => 'a',
                            'permissions' => array(
                                'module' => 'member',
                                'key' => 'consumer-delete'
                            )
                        ));
                }

                $data['aaData'][$key][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }
    public function getpostcardValueList(){
        $id = get('consumer_id');
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');
        $data = $this->mPostalCard->getUserPostcardLogList($id);
        if($data){
            foreach ($data['data'] as $key=>$value){
                $data['aaData'][$key][] = $value['name'];
                $data['aaData'][$key][] = $value['money'];
                $data['aaData'][$key][] = dateFormat($value['addtime']);
                $data['aaData'][$key][] = dateFormat($value['use_end_time']);
                $data['aaData'][$key][] = $this->mPostalCard->getLogStatus($value['status'], true);
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    public function exportUser(){

        $this->load->library('PHPExcel/PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        date_default_timezone_set('Asia/Shanghai');
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setTitle("消费者统计表")
            ->setSubject("消费者统计表")
            ->setDescription("消费者统计表")
            ->setKeywords("excel")
            ->setCategory("result file");

        //按日期查询
        $objPHPExcel->getActiveSheet()->setTitle('消费者统计');
        //构建表头
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setCellValue("A1","昵称");
        $objPHPExcel->getActiveSheet()->setCellValue("B1","电话");
        $objPHPExcel->getActiveSheet()->setCellValue("C1","真实姓名");
        $objPHPExcel->getActiveSheet()->setCellValue("D1","余额");
        $objPHPExcel->getActiveSheet()->setCellValue("E1","性别");
        $objPHPExcel->getActiveSheet()->setCellValue("F1","注册时间");
        $objPHPExcel->getActiveSheet()->setCellValue("G1","最后登录");
        $objPHPExcel->getActiveSheet()->setCellValue("H1","状态");

        $data = $this->mConsumer->adminGetList(0,true);
        $index = 2;
        foreach ($data as $k => $v) {
            $objPHPExcel->getActiveSheet()
                ->setCellValue('A'.$index, $v['nickname']?$v['nickname']:'暂无昵称')
                ->setCellValue('B'.$index, $v['mobile'])
                ->setCellValue('C'.$index,isset($v['realname']) ? $v['realname'] : '暂无')
                ->setCellValue('D'.$index, $v['balance'])
                ->setCellValue('E'.$index, $v['gender'] ? $this->mConsumer->getGender($v['gender']) : '保密')
                ->setCellValue('F'.$index, dateFormat($v['addtime'],false))
                ->setCellValue('G'.$index, isset($v['last_login_time']) ? date('Y-m-d H:i:s',$v['last_login_time']):'尚未登录');
            if($v['status']==1){
                $objPHPExcel->getActiveSheet()->setCellValue('H'.$index, "禁用");
            }else{
                $objPHPExcel->getActiveSheet()->setCellValue('H'.$index, "启用");
            }
            $index++;
        }
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="消费者统计表.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

}